# -*- coding: utf-8 -*-
"""
@FileName：test.py.py
@Description：
@Author：锦沐Python
@Time：2024/9/7 16:04
"""
import csv
import os
import re

CSV_LEARN_PATH = "D:\A-XHSPro\Tk\ReLearning\data\learn_data.csv"
def write_example_expression_data(data):
    """
    写入示例表达式
    :param data:
    """
    file_exists = os.path.isfile(CSV_LEARN_PATH) and os.path.getsize(CSV_LEARN_PATH) == 0
    with open(CSV_LEARN_PATH, 'a', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames= ["title", 'description', 'text'])
        # 写入标题行
        if file_exists:
            writer.writeheader()
        # 逐行写入数据
        for row in data:
            writer.writerow(row)

def read_example_expression_data():
    """
    读取示例表达式
    """
    with open(CSV_LEARN_PATH, 'r', newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        return list(reader)

txt1 = r"D:\A-XHSPro\Tk\ReLearning\data\create_data\learn.txt"
txt2 = r"D:\A-XHSPro\Tk\ReLearning\data\create_data\regexForSeo.txt"

with open(txt1, "r", encoding="utf-8") as file:
    csv_data = []
    learn_data = {}

    data = file.read()
    title_p = re.compile(r'(title).*', flags=re.MULTILINE|re.UNICODE)
    title_data = title_p.finditer(data)

    description_p = re.compile(r'(description).*', flags=re.MULTILINE | re.UNICODE)
    description_data = description_p.finditer(data)

    text_p = re.compile(r'(text).*', flags=re.MULTILINE | re.UNICODE)
    text_data = text_p.finditer(data)

    for index in range(68):

        learn_data = {}
        learn_data["title"] = title_data.__next__().group()[7:]
        learn_data["description"] = description_data.__next__().group()[13:]
        learn_data["text"] = text_data.__next__().group()[6:]
        print(learn_data)
        csv_data.append(learn_data)


    write_example_expression_data(csv_data)